package adminorg;

import java.util.HashSet;

import com.oros.db.*;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.ui.*;

import de.rac.vaadin.framework.ui.ListEditFormField;
import de.rac.vaadin.framework.ui.ResourcePool;

public class BPEventForm extends Accordion
{
	
	private static final long serialVersionUID = 1L;
	private BPEventMainForm bpEventMainForm;
	private BPEventTaskForm bpEventTaskForm;
	private BPEventPostForm bpEventPostForm;
	
	public BPEventForm(DatabaseHelper dbHelp) throws Exception
	{
		this.setImmediate(false);
	    bpEventMainForm = new BPEventMainForm(dbHelp);	
	    bpEventTaskForm = new BPEventTaskForm(dbHelp);
	    bpEventPostForm = new BPEventPostForm(dbHelp);
	    bpEventMainForm.activate();
	    bpEventTaskForm.activate();
	    bpEventPostForm.activate();
	    this.addTab(bpEventMainForm, dbHelp.getWords("Event"));
	    this.addTab(bpEventTaskForm,dbHelp.getWords("Task"));
	    this.addTab(bpEventPostForm,dbHelp.getWords("Post"));
	}

	public Component getBPEventForm() throws Exception {
		
		return this;
	}

 public class BPEventMainForm extends DefaultWindow {


	private static final long serialVersionUID = 7585826489324450967L;
	
    BPEventMainForm(DatabaseHelper dbHelp) throws Exception 
    {
    	super(dbHelp);
    	CompAcc_AuthColumn="isprocessadmin";
    	placeCompanyComboBoxAtRightSideOfMenu();
    }
	@Override
	public ResourcePool getActiveSpecificResource() {
		return getActiveSpecificResourceTranslated("AddingNewEvent",
				"EditingEvent","NoEventRecordIsChosen","EventDeleting",
				"EventWillBeRemoved",null);
	}

	@Override
	public AETableContainer viewTableInit() throws Exception {
         container = new AEViewContainer("EditBPEvent",new AETableContainer[]{dbHelp.getBPEventContainer()},
        		 new boolean[]{false},null,null,null,new String[]{"name"},null,null,null,null);
         addSimpleEditFormField("code","Code",true);
         addSimpleEditFormField("name","Name_NotPerson",true);
         String initiationColumn=addListEditFormField("initiation","Event",true,"ManualInitiation,PeriodInitiation,CalendarInitiation,ActionInitiation");
         String periodColumn=addDateTimeEditFormField("period","Period",false,"vvv-HH-mm",false);
         addEditFormSimpleDependence(initiationColumn,periodColumn,"initiation","equals",new Integer(1));
         String calendarColumn=addListEditFormField("calendar","CalendarType",true,"Day,Week,Month");
         addEditFormSimpleDependence(initiationColumn,calendarColumn,"initiation","equals",new Integer(2));
         String dailyColumn=addDateTimeEditFormField("daily","Time",false,"HH:mm",false);
         addEditFormSimpleDependence(initiationColumn,dailyColumn,"initiation","equals",new Integer(2));
         addEditFormSimpleDependence(calendarColumn,dailyColumn,"calendar","equals",new Integer(0));
         int options = 0;
         String startDayIsSunday=dbHelp.getWords("FirstDayOfWeekIsSunday");
         if (startDayIsSunday!=null && startDayIsSunday.trim().toUpperCase().equals("FALSE"))
         {
        	 options=ListEditFormField.OPTION_PLACEFIRSTASLAST;
         }
         String weeklyColumn=addListEditFormField("weekly","DayOfWeek",true,"SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY",options);
         addEditFormSimpleDependence(initiationColumn,weeklyColumn,"initiation","equals",new Integer(2));
         addEditFormSimpleDependence(calendarColumn,weeklyColumn,"calendar","equals",new Integer(1));
         String monthlyColumn=addSimpleEditFormField("monthly","DayOfMonth",false);
         addEditFormSimpleDependence(initiationColumn,monthlyColumn,"initiation","equals",new Integer(2));
         addEditFormSimpleDependence(calendarColumn,monthlyColumn,"calendar","equals",new Integer(2));   
         container.addGeneratedDataChecked(new AEGeneratedColumn[]{new AEGeneratedColumn("period_info",
        		 String.class,"",new AEGeneratedData(){

					
					private static final long serialVersionUID = 1L;

					@Override
					public Object generateCell(AETableContainer table,
							AERawItem item, int columnNo, int action) {
						Integer init = (Integer)item.getItemProperty("initiation").getValue();
						int initia = init==null?0:init.intValue();
						String res="";Object a;
						switch(initia)
						{
						case 1:
							a= item.getItemProperty("generated.period").getValue();
							if (a!=null) res=a.toString();
							break;
						case 2:
							Integer calendType=(Integer)item.getItemProperty("calendar").getValue();
							int calendarType=calendType==null?0:calendType.intValue();
						    switch(calendarType)
						    {
						    case 0:
						    	a= item.getItemProperty("generated.daily").getValue();
								if (a!=null) res=a.toString();
						    	break;
						    case 1:
						    	a= item.getItemProperty("generated.weekly").getValue();
								if (a!=null) res=a.toString();
						    	break;
						    case 2:
						    	a= item.getItemProperty("monthly").getValue();
								if (a!=null) res=dbHelp.getWords("DayOfMonth")+": "+ a.toString();
						    	break;
						    }
						    break;
						    
						}
						return res;
					}})});
         setLikeFilterAsAllMiddleCaseInsensitive();
         return container;
	}

	@Override
	public String[] getTranslatedViewColumnHeaders() {
		return dbHelp.getTranslatedStrings(new String[]{"Code","Name_NotPerson","Event","Parameters"});
	}

	@Override
	public String[] getViewColumns() {
		return new String[] {"code","name","generated.initiation","period_info"};
	}
	 @Override
	 public void notifyOfCompanyChange()
	 {
			super.notifyOfCompanyChange();
			bpEventTaskForm.notifyOfCompanyChange();
			bpEventPostForm.notifyOfCompanyChange();
	 }
	 @Override
	 protected void containerNewItemSelection(AERawItem item,Object itemId)
	 {
		    Object primKey=item.getPrimaryColumnValue();
		    Integer eventType =(Integer) item.getItemProperty("initiation").getValue();
		    boolean isActionType = eventType!=null && eventType.intValue()==3;
		    bpEventTaskForm.setEventParent(isActionType?primKey:null);
	 }

 }
 public class BPEventTaskForm extends DefaultWindow
 {
 	private static final long serialVersionUID = 1L;
 	private Integer currentItemId;
 	private Filter filter;
    BPEventTaskForm(DatabaseHelper dbHelp) throws Exception
    {
    	super(dbHelp);
    	CompAcc_AuthColumn="isprocessadmin";
        container = new AEViewContainer("EditBPEventTask",new AETableContainer[]{dbHelp.getBPEventTaskContainer(),
       		 dbHelp.getBPTaskContainer()},
       		 new boolean[]{false,true},new String[]{"bpeventtask.task"},null,null,null,null,null,null,null);
        
        addTableListEditFormField("bpeventtask.task","Task",true,"bptask(name)");
        setLikeFilterAsAllMiddleCaseInsensitive();
    }
	@Override
	public ResourcePool getActiveSpecificResource() {
		return getActiveSpecificResourceTranslated("AddingNewBPEventTask",
				"EditingBPEventTask","NoBPEventTaskRecordIsChosen","BPEventTaskDeleting",
				"BPEventTaskRecordWillBeRemoved","BPEventTaskMustBeUnique");
	}

	@Override
	public String[] getTranslatedViewColumnHeaders() {
		return dbHelp.getTranslatedStrings(new String[]{"Task"});
	}

	@Override
	public String[] getViewColumns() {
		return new String[] {"bptask.name"};
	} 
	 public void setEventParent(Object id)
     {
		 
		 bpEventPostForm.setEventTaskParent(null);
     	if (id==null) {currentItemId=null;}
     	else
     	{
     	   if (id instanceof Integer) currentItemId=(Integer)id;
     	     else currentItemId=new Integer(Integer.parseInt(id.toString()));
     	   if (currentItemId.intValue()<=0) currentItemId=null;
     	}
     	if (currentItemId!=null)
     	{
     	   if (filter!=null) container.removeContainerFilter(filter);
		   filter = new Compare.Equal("bpeventtask.event", currentItemId);
		   container.addContainerFilter(filter);
     	}
     	ensureDisableFormPanel();
     }
	 @Override
	 public void notifyOfCompanyChange()
	 {
			currentItemId=null;
			super.notifyOfCompanyChange();
	 }
     @Override
     public boolean isFormReadyForNewEditDelete()
     {
         return currentItemId!=null;
     }
	 @Override
	 protected void containerNewItemSelection(AERawItem item,Object itemId)
	 {
		    Object primKey=item.getPrimaryColumnValue();
		    bpEventPostForm.setEventTaskParent(primKey);
	 }
     @Override
     protected Object createNewRowItem(AETableContainer table) throws Exception
	 {
     	Object id = super.createNewRowItem(table);
     	setNewEditItemField("bpeventtask.event",currentItemId);
     	return id;
	 }
 }
 public class BPEventPostForm extends DefaultWindow
 {
		private static final long serialVersionUID = 1L;
		private Integer currentItemId;
		private AEViewContainer editContainer;
		private AETableContainer srcContainer,bppostContainer;
		private Filter filter;
	    BPEventPostForm(DatabaseHelper dbHelp)
	    {
	    	super(dbHelp);
	    	CompAcc_AuthColumn="isprocessadmin";
	    }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPEventPost",
					"EditingBPEventPost","NoBPEventPostRecordIsChosen","BPEventPostDeleting",
					"BPEventPostRecordWillBeRemoved","BPEventPostMustBeUnique");
		}

		@Override
		public AETableContainer viewTableInit() throws Exception {
			 editContainer = dbHelp.views.getEventPostTaskContainer();
			 bppostContainer = dbHelp.getBPPostContainer();
			 srcContainer = dbHelp.getBPEventTaskContainer();
	         container = new AEViewContainer("EditBPEventPost",new AETableContainer[]{dbHelp.getBPEventPostContainer(),
	        		 dbHelp.getOrgschemaReadContainer()},
	        		 new boolean[]{false,true},new String[]{"bpeventpost.post"},null,null,null,null,null,null,null);
	         
	         addTableListEditFormField("bpeventpost.post","Post",true,"EventPostTask(post_name)");
	         setLikeFilterAsAllMiddleCaseInsensitive();
	         return container;
		}
        public void setEventTaskParent(Object id)
        {
        	if (id==null) {currentItemId=null;}
        	else
        	{
        	   if (id instanceof Integer) currentItemId=(Integer)id;
        	   else currentItemId=new Integer(Integer.parseInt(id.toString()));
        	   if (currentItemId.intValue()<=0) currentItemId=null;
        	}
        	if (currentItemId!=null)
        	{
        		Integer taskId=(Integer)srcContainer.getContainerProperty(currentItemId, "task").getValue();
        		if (taskId==null) currentItemId=null; //this must never be if no errors
        		else
        		{
        			HashSet<?> postFilterSrc=bppostContainer.getDistinctColumnValues("post", new Filter[]{new Compare.Equal("task", taskId)});
        			editContainer.cleanAndAddContainerFilter(new AEInFilter("id",postFilterSrc));
        			if (filter!=null) container.removeContainerFilter(filter);
        			filter = new Compare.Equal("bpeventpost.eventtask", currentItemId);
        			container.addContainerFilter(filter);
        		}
        	}
        	ensureDisableFormPanel();
        }
		@Override
		public void notifyOfCompanyChange()
		{
			currentItemId=null;
			super.notifyOfCompanyChange();
		}
        @Override
        public boolean isFormReadyForNewEditDelete()
        {
            return currentItemId!=null;
        }
        @Override
        protected Object createNewRowItem(AETableContainer table) throws Exception
		{
        	Object id=super.createNewRowItem(table);
        	setNewEditItemField("bpeventpost.eventtask",currentItemId);
        	return id;
		}		
		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"Post"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"orgschema.post_name"};
		} 	 
 }
}